package org.jeecg.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.modules.entity.DbContract;
import org.jeecg.modules.entity.DbFinanceManage;
import org.jeecg.modules.entity.DbInvoiced;
import org.jeecg.modules.mapper.DbContractMapper;
import org.jeecg.modules.mapper.DbFinanceManageMapper;
import org.jeecg.modules.mapper.DbInvoicedMapper;
import org.jeecg.modules.service.IDbContractService;
import org.jeecg.modules.service.IDbFinanceManageService;
import org.jeecg.modules.service.IDbInvoicedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: db_invoiced
 * @Author: jeecg-boot
 * @Date:   2024-06-13
 * @Version: V1.0
 */
@Service
public class DbInvoicedServiceImpl extends ServiceImpl<DbInvoicedMapper, DbInvoiced> implements IDbInvoicedService {

    @Autowired
    private IDbContractService dbContractService;
    @Autowired
    private IDbFinanceManageService dbFinanceManageService;
    /**
     * 添加开票和计算开票总金额
     * @param dbInvoiced
     */
    @Transactional
    public void add(DbInvoiced dbInvoiced) {
        this.save(dbInvoiced);
        updateAmountById(dbInvoiced);
    }

    @Transactional
    public void removeAmountById(String id) {
        DbInvoiced dbInvoiced = this.getById(id);
        this.removeById(id);
        updateAmountById(dbInvoiced);
    }

    public void updateAmountById(DbInvoiced dbInvoiced) {
        QueryWrapper<DbInvoiced> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id",dbInvoiced.getContractId()).eq("deleted",0);
        List<DbInvoiced> dbInvoiceds = this.list(queryWrapper);
        BigDecimal invoiceAmount = new BigDecimal(0);
        for (DbInvoiced invoiced : dbInvoiceds) {
            invoiceAmount = invoiceAmount.add(invoiced.getAmount());
        }
        UpdateWrapper<DbContract> contractUpdateWrapper = new UpdateWrapper<>();
        contractUpdateWrapper.set("invoice_amount",invoiceAmount).eq("contract_id",dbInvoiced.getContractId());
        dbContractService.update(null,contractUpdateWrapper);
        UpdateWrapper<DbFinanceManage> financeManageUpdateWrapper = new UpdateWrapper<>();
        financeManageUpdateWrapper.set("invoice_amount",invoiceAmount).eq("contract_id",dbInvoiced.getContractId());
        dbFinanceManageService.update(null,financeManageUpdateWrapper);
    }
}
